const winston = require('winston');
const path = require('path');
const fs = require('fs');

// 确保日志目录存在
const logDir = path.join(__dirname, '../../logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 定义日志级别
const levels = {
  error: 0,
  warn: 1,
  info: 2,
  http: 3,
  debug: 4,
};

// 根据环境确定日志级别
const level = () => {
  const env = process.env.NODE_ENV || 'development';
  return env === 'development' ? 'debug' : 'warn';
};

// 定义日志颜色
const colors = {
  error: 'red',
  warn: 'yellow',
  info: 'green',
  http: 'magenta',
  debug: 'white',
};

// 添加颜色
winston.addColors(colors);

// 定义日志格式
const format = winston.format.combine(
  // 添加时间戳
  winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),
  // 添加颜色
  winston.format.colorize({ all: true }),
  // 自定义格式
  winston.format.printf(
    (info) => `${info.timestamp} ${info.level}: ${info.message}`,
  ),
);

// 定义日志传输方式
const transports = [
  // 控制台输出
  new winston.transports.Console(),
  
  // 错误日志文件
  new winston.transports.File({
    filename: path.join(logDir, 'error.log'),
    level: 'error',
  }),
  
  // 所有日志文件
  new winston.transports.File({ 
    filename: path.join(logDir, 'combined.log') 
  }),
];

// 创建日志实例
const logger = winston.createLogger({
  level: level(),
  levels,
  format,
  transports,
});

// 创建HTTP请求日志中间件
const httpLogger = (req, res, next) => {
  // 记录请求开始时间
  const start = Date.now();
  
  // 请求完成时记录日志
  res.on('finish', () => {
    const duration = Date.now() - start;
    const message = `${req.method} ${req.originalUrl} ${res.statusCode} ${duration}ms`;
    
    // 根据状态码确定日志级别
    if (res.statusCode >= 500) {
      logger.error(message);
    } else if (res.statusCode >= 400) {
      logger.warn(message);
    } else {
      logger.http(message);
    }
  });
  
  next();
};

// 创建错误日志函数
const logError = (err, req = null) => {
  const errorDetails = {
    message: err.message,
    stack: err.stack,
    timestamp: new Date().toISOString(),
  };
  
  // 如果有请求对象，添加请求信息
  if (req) {
    errorDetails.method = req.method;
    errorDetails.url = req.originalUrl;
    errorDetails.ip = req.ip;
    errorDetails.user = req.user ? req.user._id : 'anonymous';
  }
  
  logger.error(`Error: ${err.message}`, { errorDetails });
  
  return errorDetails;
};

module.exports = {
  logger,
  httpLogger,
  logError,
}; 